const Router = require("@koa/router");
const router = new Router();
const jwt = require("jsonwebtoken");
const {Sequelize, DataTypes, where} = require("sequelize");
// 验证用户身份的中间件
const authenticateUser = async (ctx, next) => {
  const token = ctx.headers.authorization;

  if (!token) {
    ctx.status = 401;
    ctx.body = {error: "未提供身份验证令牌。"};
    return;
  }

  // 解码 base64 编码的 token
  const decodedToken = Buffer.from(token, "base64").toString("utf-8");

  jwt.verify(decodedToken, "token", (err, decoded) => {
    if (err) {
      ctx.status = 401;
      ctx.body = {error: "无效的身份验证令牌。"};
      return;
    }

    ctx.state.userId = decoded.userId;
  });

  await next();
};

//获取详情菜单
router.get("/Detailed_Menu", async (ctx, next) => {
  try {
    // 检查请求头部中是否包含 token
    const token = ctx.header.authorization;
    if (!token) {
      ctx.status = 401; // 未授权
      ctx.body = {success: false, error: "未提供身份验证信息，请登录账户。"};
      return;
    }

    // 如果请求头部中包含 token，则继续处理请求
    const id =ctx.query.id; // 获取订单ID，默认为1
    console.log(id)
    // 查询订单详细信息
    const order = await ctx.state.Order.findOne({
      where: {id: id},
    });

    if (!order) {
      ctx.status = 404;
      ctx.body = {success: false, error: "订单不存在。"};
      return;
    }

    // 解析订单详情中的菜品信息
    let odermenulist = {orderItems: [], totalPrice: 0};
    let totalPrice = 0;
    const orderItems = JSON.parse(order.order_msg);
    if (orderItems.length > 0) {
      for (const item of orderItems) {
        const dish = await ctx.state.Menu.findByPk(item.dishid);
        const menu = {
          dishName: dish.dishName,
          oneprice: dish.price,
          image: dish.image,
          Quantity: item.remainingQuantity,
          sumprice: dish.price * item.remainingQuantity,
        };
        odermenulist.orderItems.push(menu);
        totalPrice += dish.price * item.remainingQuantity;
      }

      odermenulist.totalPrice = totalPrice;
    } else {
      ctx.status = 201;
      ctx.body = {success: false, error: "无点单信息。"};
      return;
    }
    ctx.status = 200;
    ctx.body = {
      success: true,
      orderItems: odermenulist,
    };
  } catch (error) {
    console.error("Error fetching order details:", error);
    ctx.status = 500;
    ctx.body = {success: false, error: "获取菜单详情时发生错误。"};
  }
});

// 获取订单列表
router.post("/GetOrders", authenticateUser, async (ctx) => {
  try {
    let {
      table_number,
      transac_status,
      startTime,
      endTime,
      order_msg,
      price,
      page,
    } = ctx.request.body;
    const pageSize = 10;
    const offset = (page - 1) * pageSize;

    const whereClause = {};

    // 如果存在桌号，进行精确查询
    if (table_number) {
      whereClause.table_number = table_number;
    }

    // 如果存在交易状态，进行精确查询
    if (transac_status) {
      whereClause.transac_status = transac_status;
    }

    // 如果存在交易时间，进行范围查询
    if (startTime && endTime) {
      // 将字符串日期转换为 Date 对象
      startTime = new Date(startTime);
      endTime = new Date(endTime);
      // 指定时间范围查询
      whereClause.order_time = {
        [Sequelize.Op.gte]: startTime, // 大于等于开始时间
        [Sequelize.Op.lte]: endTime, // 小于等于结束时间
      };
    }

    // 如果存在订单信息，进行模糊查询
    if (order_msg) {
      whereClause.order_msg = {[Sequelize.Op.like]: `%${order_msg}%`};
    }

    // 如果存在价格，进行范围查询
    if (price) {
      whereClause.price = {[Sequelize.Op.like]: `%${price}%`};
    }

    // 查询符合条件的订单列表，并按订单时间从新到旧排序
    const orders = await ctx.state.Order.findAll({
      where: whereClause,
      order: [["order_time", "DESC"]],
      limit: pageSize,
      offset: offset,
    });

    // 查询数据总数
    const total = await ctx.state.Order.count({where: whereClause});

    ctx.status = 200;
    ctx.body = {orders, total};
  } catch (error) {
    console.error("Error fetching orders:", error);
    ctx.status = 500;
    ctx.body = {error: "获取订单时发生错误。"};
  }
});

// 创建新订单
router.post("/AddOrders", authenticateUser, async (ctx) => {
  try {
    const {
      //order_time,
      table_number,
      order_msg,
      transac_status,
      number_of_diners,
    } = ctx.request.body;

    // 将 order_msg 数组转换为字符串
    const orderMsgString = JSON.stringify(order_msg);

    // 根据 order_msg 计算总价格
    let totalPrice = 0;
    for (const item of order_msg) {
      const dish = await ctx.state.Menu.findByPk(item.dishid);
      totalPrice += dish.price * item.remainingQuantity;
    }

    // 创建新订单
    const newOrder = await ctx.state.Order.create({
      // order_time,
      table_number,
      order_msg: orderMsgString, // 将转换后的字符串赋值给订单
      transac_status,
      number_of_diners,
      price: totalPrice.toFixed(2), // 价格保留两位小数
    });

    ctx.status = 201;
    ctx.body = {message: "订单创建成功。", order: newOrder};
  } catch (error) {
    console.error("创建订单时出错:", error);
    ctx.status = 500;
    ctx.body = {error: "创建订单时发生错误。"};
  }
});

// 修改订单
router.post("/orders_update", authenticateUser, async (ctx) => {
  try {
    const orderId = ctx.request.body.id;
    const {
      order_time,
      table_number,
      order_msg,
      transac_status,
      number_of_diners,
      price,
    } = ctx.request.body;

    const orderToUpdate = await ctx.state.Order.findByPk(orderId);

    if (!orderToUpdate) {
      ctx.status = 404;
      ctx.body = {error: "找不到要修改的订单。"};
      return;
    }

    await ctx.state.OrderToUpdate.update({
      order_time,
      table_number,
      order_msg,
      transac_status,
      number_of_diners,
      price,
    });

    ctx.status = 200;
    ctx.body = {message: "订单修改成功。", order: orderToUpdate};
  } catch (error) {
    console.error("Error updating order:", error);
    ctx.status = 500;
    ctx.body = {error: "修改订单时发生错误。"};
  }
});

// 删除订单
router.post("/order_delete", authenticateUser, async (ctx) => {
  try {
    const orderId = ctx.request.body.id;
    const orderToDelete = await ctx.state.Order.findByPk(orderId);

    if (!orderToDelete) {
      ctx.status = 404;
      ctx.body = {error: "找不到要删除的订单。"};
      return;
    }

    await ctx.state.OrderToDelete.destroy();
    ctx.status = 200;
    ctx.body = {message: "订单删除成功。"};
  } catch (error) {
    console.error("Error deleting order:", error);
    ctx.status = 500;
    ctx.body = {error: "删除订单时发生错误。"};
  }
});

// 获取桌子列表
router.post("/gettablelist", authenticateUser, async (ctx) => {
  try {
    const {table_name, table_number} = ctx.request.body;

    const whereClause = {};

    // 如果存在桌名，进行模糊查询
    if (table_name) {
      whereClause.table_name = {[Sequelize.Op.like]: `%${table_name}%`};
    }

    // 如果存在桌号，进行模糊查询
    if (table_number) {
      whereClause.table_number = {[Sequelize.Op.like]: `%${table_number}%`};
    }

    // 查询符合条件的桌子列表，并按桌号从小到大排序
    const tables = await ctx.state.Table.findAll({
      where: whereClause,
      order: [["table_number", "ASC"]],
    });

    // 查询数据总数
    const total = await ctx.state.Table.count({where: whereClause});

    ctx.status = 200;
    ctx.body = {tables, total};
  } catch (error) {
    console.error("Error fetching tables:", error);
    ctx.status = 500;
    ctx.body = {error: "获取桌子列表时发生错误。"};
  }
});

// 创建新桌子
router.post("/tableadd", authenticateUser, async (ctx) => {
  try {
    const {table_name, table_number} = ctx.request.body;

    // 检查是否存在相同桌号或桌名的桌子
    const existingTable = await ctx.state.Table.findOne({
      where: {[Sequelize.Op.or]: [{table_name}, {table_number}]},
    });

    if (existingTable) {
      ctx.status = 400;
      ctx.body = {error: "该桌号或桌名已经存在，请使用其他桌号或桌名。"};
      return;
    }

    // 创建新的桌子
    const newTable = await ctx.state.Table.create({
      table_name,
      table_number,
    });

    ctx.status = 201;
    ctx.body = {message: "桌子创建成功。", table: newTable};
  } catch (error) {
    console.error("Error creating table:", error);
    ctx.status = 500;
    ctx.body = {error: "创建桌子时发生错误。"};
  }
});

// 修改桌子
router.post("/uptables", authenticateUser, async (ctx) => {
  try {
    const tableId = ctx.request.body.id;
    const {table_name, table_number} = ctx.request.body;

    const tableToUpdate = await ctx.state.Table.findByPk(tableId);

    if (!tableToUpdate) {
      ctx.status = 404;
      ctx.body = {error: "找不到要修改的桌子。"};
      return;
    }

    await ctx.state.TableToUpdate.update({
      table_name,
      table_number,
    });

    ctx.status = 200;
    ctx.body = {message: "桌子修改成功。", table: tableToUpdate};
  } catch (error) {
    console.error("Error updating table:", error);
    ctx.status = 500;
    ctx.body = {error: "修改桌子时发生错误。"};
  }
});

// 删除桌子
router.post("/deleteTb", authenticateUser, async (ctx) => {
  try {
    const tableId = ctx.request.body.id;
    const tableToDelete = await ctx.state.Table.findByPk(tableId);

    if (!tableToDelete) {
      ctx.status = 404;
      ctx.body = {error: "找不到要删除的桌子。"};
      return;
    }

    await ctx.state.TableToDelete.destroy();
    ctx.status = 200;
    ctx.body = {message: "桌子删除成功。"};
  } catch (error) {
    console.error("Error deleting table:", error);
    ctx.status = 500;
    ctx.body = {error: "删除桌子时发生错误。"};
  }
});

module.exports = router;
